package com.springcloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.springcloud.common.Friend;
import com.springcloud.requestcache.RequestCacheService;
import com.springcloud.service.MyService;
import lombok.Cleanup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 顾志杰
 */
@RestController
public class Controller {

    @Autowired
    private MyService myService;

    @Autowired
    private RequestCacheService requestCacheService;

    @GetMapping("/fallback")
    public String error() {
        return myService.error();
    }

    @GetMapping("/timeout")
    public String timeout(Integer timeout) {
        return myService.retry(timeout);
    }

    @GetMapping("/timeout2")
    @HystrixCommand(
            fallbackMethod = "timeoutFallback",
            commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String timeout2(Integer timeout) {
        return myService.retry(timeout);
    }

    private String timeoutFallback(Integer timeout){
        return "success";
    }

    @GetMapping("/cache")
    public Friend cache(String name) {
        /*声明HystrixRequest上下文
        @Cleanup 默认调用方法中的close方法 如果方法名不是close 可以根据value数据自行更改
         */
        @Cleanup HystrixRequestContext context = HystrixRequestContext.initializeContext();
        Friend friend;
        friend = requestCacheService.RequestCache(name);
        friend = requestCacheService.RequestCache(name);
        return friend;
    }
}
